<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'meta.title', key: 'permissionId' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import {
    setPermissions,
    permissionTree,
    addRole,
    getPermissionsByRoleIdAPI,
  } from '@/api/demo/system';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const roleId = ref(null);
  const treeData = ref([]);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    let router = await permissionTree('menu');

    function convertMeta(items) {
      return items.map((item) => {
        if (item.meta) {
          item.meta = JSON.parse(item.meta);
        }
        if (item.children && item.children.length > 0) {
          item.children = convertMeta(item.children);
        }
        return item;
      });
    }

    treeData.value = convertMeta(router.data);
    isUpdate.value = !!data?.isUpdate;
    roleId.value = data?.record?.roleId || null;

    if (unref(isUpdate)) {
      const permissions = await getPermissionsByRoleIdAPI(roleId.value);
      const menuValues = permissions.data;
      setFieldsValue({
        ...data.record,
        menu: menuValues,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    let Data;
    try {
      const values = await validate();
      if (roleId.value !== null) {
        values.roleId = roleId.value; // 添加 roleId 到提交的数据中
      }
      const menu = values.menu;
      if (menu) {
        const permissionIds = Object.values(menu);
        values.permissionIds = permissionIds;
      }
      if (isUpdate.value) {
        Data = await setPermissions(values);
        console.log(Data, '编辑权限');
      } else {
        Data = await addRole(values);
        console.log(Data, '添加权限');
      }
      setDrawerProps({ confirmLoading: true });
      console.log(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
